package com.powergisol.gis.controller;

import com.powergisol.gis.util.MachineCodeUtil;
import com.powergisol.gis.util.RSAUtil;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("security")
public class SecurityController {

    /**
     * 生成机器码
     * @return
     */
    @GetMapping("machineCode")
    public String machineCode(){
        return MachineCodeUtil.generateMachineCode();
    }

    /**
     * 生成密文数据以及私钥
     * @param machineCode 机器码(BASE64)
     */
    @GetMapping("generate/{machineCode}")
    public ResponseEntity<byte[]> generate(@PathVariable(required = true) String machineCode){
        try {
            //生成密钥对
            Map<String, Object> keyMap = RSAUtil.genKeyPair();
            String pubKey = RSAUtil.getPublicKey(keyMap);
            String priKey = RSAUtil.getPrivateKey(keyMap);
            //公钥加密
            byte[] encryptByte = RSAUtil.encryptByPublicKey(machineCode.getBytes(), pubKey);
            //密文数据加密
            String base64Data = Base64.encodeBase64String(encryptByte);
            //数据返回(密文数据+私钥)
            String resultData = base64Data+"\r\n"+priKey;
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attchement;filename=rsa.pri");
            HttpStatus statusCode = HttpStatus.OK;
            ResponseEntity<byte[]> entity = new ResponseEntity<>(resultData.getBytes(), headers, statusCode);
            return entity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据密文数据和私钥进行解密认证
     * @param data 密文数据
     * @param priKey 私钥
     * @return
     */
    @GetMapping("check/{data}/{priKey}")
    public boolean check(@PathVariable String data, @PathVariable String priKey){
        //BASE64解码
        byte[] dcryptBase64Data = Base64.decodeBase64(data);
        try {
            //私钥解密
            String dcryptMachineCode = new String(RSAUtil.decryptByPrivateKey(dcryptBase64Data, priKey));
            //比对
            if (dcryptMachineCode.equals(MachineCodeUtil.generateMachineCode())) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
